from mailbox import mbox, Maildir
import sys

def cleanup_mbox(mybox, logf):
    prev_k = None
    for k in mybox.keys():
        msg = mybox[k]
        if len(msg.keys()) < 2:
            text = msg.as_string()
            
            if prev_k is None:
                continue
            
            prev_msg = mybox[prev_k]
            
            parent_prev_msg = prev_msg
            
            # WARNING: if there is a multipart-multipart message, this will crash
            if parent_prev_msg.is_multipart():
                while prev_msg.is_multipart():
                    prev_msg = prev_msg.get_payload()[-1]
            
            text = prev_msg.get_payload() + "\n>From " + msg.get_from() + "\n" + text
            prev_msg.set_payload(text)
            
            logf.write("One msg is cleaned up in " + mybox._path + "\n")
            logf.flush()
            mybox.update([(prev_k, parent_prev_msg)])
            mybox.remove(k)
        else:
            prev_k = k
    
    mybox.flush()

if __name__ == "__main__":
    cleanup_mbox(mbox(sys.argv[1]))
